package com.atmilan.quartz.utils.source;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.StockAreaTempEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.efasion.EfasionProduct;
import com.atmilan.quartz.model.entity.efasion.EfasionProductSku;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

/**
 * 处理源数据转换和计算相关信息
 * @Description: 
 * @author daigb
 * @date 2021-03-05
 */
@Service
public class SourceEfasionProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;
    
    /**
     * 构建DO对象
     * @Description:  
     * @author daigb 
     * @param @param product
     * @param @param productSkus
     * @param @return
     * @return StoreProductRequest
     * @throws
     */
    public StoreProductCrmebRequest buildProduct(EfasionProduct product, List<EfasionProductSku> productSkus) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = null;
        try {
            EfasionProductSku minSku = productSkus.stream().min(Comparator.comparing(EfasionProductSku :: getPrice)).get();
            // 成本价
            BigDecimal erpPrice = priceUtil.eur2RmbStatic(minSku.getPrice());
            // 市场价(欧元)
            BigDecimal retailPrice = minSku.getOtPrice();
            
            // 品牌对应
            StoreBrand storeBrand = null == product.getBrandId() ? null : storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand :: getOtherId, product.getBrandId())
                    .eq(StoreBrand :: getType, ProductTypeEnum.EFASION)
                    .last("LIMIT 1")
                    );
            storeBrandService.unMatchBrand(storeBrand, product.getBrandId() + "", null, ProductTypeEnum.EFASION);
            // 5429 其他品牌
            if(null == storeBrand){
                storeBrand = storeBrandService.getById(5429);
            }

            /***** 处理对象构建 *******/
            String barCode = BarCodeEnum.EFASION.getCode() + product.getProductId().toString();
            List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();

            // 规格
            StoreProductAttr storeProductAttr = new StoreProductAttr();
            storeProductAttr.setAttrName("尺寸");
            storeProductAttr.setType(0);
            // 颜色
            StoreProductAttr storeProductAttrColor = new StoreProductAttr();
            storeProductAttrColor.setAttrName("颜色");
            storeProductAttrColor.setType(0);
            // 合并成suk
            List<String> colorValueList = new ArrayList<String>();
            List<String> valueList = new ArrayList<String>();
            for(EfasionProductSku sku : productSkus) {
                // 成本价
                BigDecimal erpSkuPrice = priceUtil.eur2RmbStatic(sku.getPrice());
                // 市场价
                BigDecimal retailSkuPrice = sku.getOtPrice();
                // value对象
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setSourceSkuId(sku.getSourceSkuId());
                
                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<String, String>();
                List<String> suk = new ArrayList<String>();
                String color = sku.getSuk().contains(",") ? sku.getSuk().split(",")[0] : null;
                if (StringUtils.isNotBlank(color)) {
                    linkedMap.put("颜色", color);
                    if(!colorValueList.contains(color)){
                        colorValueList.add(color);
                    }
                    suk.add(color);
                }
                String[] suks = sku.getSuk().split(",");
                String size = suks.length > 1 ? suks[1] : suks[0];
                if (StringUtils.isNotBlank(size)) {
                    linkedMap.put("尺寸", size);
                    if(!valueList.contains(size)){
                        valueList.add(size);
                    }
                    suk.add(size);
                }

                storeProductAttrValue.setSuk(String.join(",", suk));
                storeProductAttrValue.setStock(sku.getStock());
                storeProductAttrValue.setPrice(erpSkuPrice);
                storeProductAttrValue.setImage(StringUtils.isBlank(sku.getImage()) ? product.getImage() : sku.getImage());
                storeProductAttrValue.setCost(erpSkuPrice);
                storeProductAttrValue.setSourceCost(erpSkuPrice);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(retailSkuPrice);
                
                storeProductAttrValue.setAttrValue(linkedMap);
                attrValueList.add(storeProductAttrValue);
            }
            if (CollectionUtils.isNotEmpty(colorValueList)) {
                storeProductAttrColor.setAttrValues(String.join(",", colorValueList));
                attrList.add(storeProductAttrColor);
            }
            if (CollectionUtils.isNotEmpty(valueList)) {
                storeProductAttr.setAttrValues(String.join(",", valueList));
                attrList.add(storeProductAttr);
            }
            
            productRequest = new StoreProductCrmebRequest();
//            productRequest.setExchangeRate(priceResult.getExchangeRate());
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.EFASION.getMerchantId());
            productRequest.setContent(product.getStoreInfo());
            productRequest.setKeyword(product.getKeyword());
            productRequest.setStoreInfo(product.getStoreInfo());
            productRequest.setStoreName(product.getStoreName());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(erpPrice);
            productRequest.setOtPrice(retailPrice);
            productRequest.setCost(erpPrice);
            productRequest.setSourceCost(erpPrice);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            // 易时尚单独香港仓
            if(product.getTempId() == StockAreaTempEnum.EUR.getTempId()) {
            	productRequest.setTempId(StockAreaTempEnum.EUR.getTempId());
            } else {
            	if(product.getBarcode().startsWith("9000")) {
            		productRequest.setTempId(StockAreaTempEnum.HK_EFASION.getTempId());
            	} else {
            		productRequest.setTempId(StockAreaTempEnum.HK.getTempId());
            	}
            }

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier :: getBarcode, BarCodeEnum.EFASION.getCode())
                    .last("LIMIT 1")
                    );
            if(null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }
            productRequest.setBarCode(barCode);
            // 分类
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch :: getType, CategoryTypeEnum.EFASION)
                    .eq(CategoryMatch :: getOthCategoryId, product.getCateId())
                    .last("LIMIT 1")
                    );
            categoryMatchService.unMatchCategory(categoryMatch, product.getCateId(), null, null, CategoryTypeEnum.EFASION);
            // 复制重量(标准分类重量)
            if(null != categoryMatch) {
            	CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
            	categoryMatch.setWeight(supCategoryMatch.getWeight());
            }
            Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 1859;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Arrays.asList(categoryId));
            productRequest.setWeight(null != categoryMatch ? categoryMatch.getWeight() : BigDecimal.ONE);
            productRequest.setImage(product.getImage());
            productRequest.setSliderImage(product.getSliderImage());
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.EFASION.getCode());
            productRequest.setUnitName(product.getUnitName());
            BigDecimal exchangeRate = priceUtil.getMoneyExchange(supplier.getCurrencyId());
            productRequest.setExchangeRate(exchangeRate);
//            productRequest.setExchangeRate(new BigDecimal(PriceUtil.DEFAULT_EXCHANGE_RATE_EUR));
//            productRequest.setComposition(product.getComposition());
//            productRequest.setDimension(product.getDimension());
//            productRequest.setColorCode(product.getColorCode());
//            productRequest.setSeasonCode(product.getSeasonCode());
            
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return productRequest;
    }
    
}
